<template>
	<div>
		<img ref="el" :src="realSrc" alt="" :style="{ width: width, height: height }" />
	</div>
</template>

<script setup lang="ts">
import loading from '@/assets/loading.gif'
import error from '@/assets/error.webp'
import { defineProps, onMounted, ref } from 'vue'
const props = defineProps(['width', 'height', 'src']);
const realSrc = ref(loading)
const el = ref<null | HTMLImageElement>(null)
// 读取图片
const loadImg = () => {
	const img = new Image();
	img.src = props.src
	img.addEventListener('load', () => {
		realSrc.value = props.src
	})

	img.addEventListener('error', () => {
		realSrc.value = error
	})
}


onMounted(() => {
	if (el.value !== null) {
		// 监听元素会否进入视口
		// 创建实例
		const o = new IntersectionObserver((entries) => {
			entries.forEach(v => {
				// 元素位置信息
				if (v.isIntersecting) {
					loadImg()
					o.unobserve(el.value as Element)
				}
			})
		})
		// 监听元素
		o.observe(el.value)
	}
})
</script>